package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.api.common.entity.Tickets;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.service.TicketsService;
import com.hitqz.robot.driver.model.IRobotPosDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author xupkun
 * @date 2025/3/21
 */
@Slf4j
@LiteflowComponent(value = "CallSwitchModuleTask", name = "[轮对/轮轴]呼叫平衡重叉车流程")
@AllArgsConstructor

public class CallSwitchModuleTask extends NodeComponent {

    private final RestTemplate restTemplate;

    private final RobotDriverService robotDriverService;

    private final TicketsService ticketsService;

    private final RobotService robotService;


    private static final String baseUrl = "http://127.0.0.1:8900/api/fms";

    private final RobotMapPosService robotMapPosService;

    /**
     * 添加移动任务
     */
    private static final String addTask = baseUrl + "/addTask";

    @Override
    public void process() throws Exception {
        try {
            FlowContextDto dto =  this.getRequestData();
            TicketsTask task = dto.getTicketsTask();
            Tickets tickets = ticketsService.getById(task.getTicketsId());
            String taskName = tickets.getName().split("--")[0];
            IRobotPosDto robotPosDto = robotDriverService.getWebPos();
            Robot robot = robotService.getDefaultRobot();
            FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                    .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
            String sourceName = Optional.ofNullable(ticketsDto.getModalData().get("sourcePosName"))
                    .orElse(ticketsDto.getModalData().get("sourcePosCode")).toString();
            sourceName = sourceName.trim();
            String targetName = ticketsDto.getModalData().get("targetPosName")== null ?
                    String.valueOf(ticketsDto.getModalData().get("targetPosCode")):
                    String.valueOf(ticketsDto.getModalData().get("targetPosName"));
            targetName = targetName.trim();
            log.info("任务名称: {}--{}---{}", taskName, sourceName, targetName);
            RobotMapPos sourcePos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                    .eq(RobotMapPos::getName, sourceName)
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            if (sourcePos == null) {
                sourcePos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                        .eq(RobotMapPos::getCode, sourceName)
                        .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            }
            //log.info("source:" + JSONObject.toJSONString(sourcePos));
            List<RobotMapPos> preSourcePosList = robotMapPosService.list(Wrappers.<RobotMapPos>lambdaQuery()
                    .like(RobotMapPos::getPreCode, sourcePos.getCode())
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            RobotMapPos finalSourcePos = sourcePos;
            AtomicReference<RobotMapPos> preSourcePos = new AtomicReference<>();
            preSourcePosList.forEach(t-> {
                if (Arrays.stream(t.getPreCode().split(",")).anyMatch(s-> s.equals(finalSourcePos.getCode()))) {
                    preSourcePos.set(t);
                }
            });
            RobotMapPos targetPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                    .eq(RobotMapPos::getName, targetName)
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            if (targetPos == null) {
                targetPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                        .eq(RobotMapPos::getCode, targetName)
                        .eq(RobotMapPos::getMapCode, robot.getMapCode()));
            }

            int Priority = taskName.contains("轮轴支出") ? 0 : 1;
            String taskNo = taskName + System.currentTimeMillis();
            if (robotPosDto.getFull()) {
                taskName = taskName + "-带载";
            }
            Map<String, Object> requestParams = Maps.newHashMap();
            requestParams.put("TaskNo", taskNo);
            requestParams.put("Priority", Priority);
            requestParams.put("VehicleNo", robot.getRobotSn());
            requestParams.put("FinishAction", 0);
            requestParams.put("TaskType", taskName);
            requestParams.put("des", targetPos.getCode());
            requestParams.put("src", sourcePos.getCode());
            requestParams.put("pre_src", preSourcePos.get().getCode());
            // 空托盘位置， 暂时固定后续方案确定再进行修改
            requestParams.put("middle_src", "33");
            String requestBody = JSONObject.toJSONString(requestParams);
            sendDispatch(requestBody, addTask);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private String sendDispatch(String requestBody, String uri) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>( requestBody, headers);
            log.info("请求地址{} 参数: {}", uri
                    , requestBody);
            String response = restTemplate.postForObject(uri, requestEntity, String.class);
            log.info("任务返回接果: " + response);
            return response;
        } catch (Exception e) {
            log.info("请求地址发生异常:" + e.getMessage());
        }
        return null;
    }



}
